import random
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
import string
class EmailService:

    @classmethod
    def send_email_invite(cls, email: str, url: str, inviter: str, team_name: str):
        # 1. 连接到SMTP服务器
        smtpObj = smtplib.SMTP('smtp.qq.com', 587)
        # 2. 发送SMTP的“HELLO”消息
        smtpObj.ehlo()
        # 3. 开始TLS加密
        smtpObj.starttls()
        # 4. 登陆到SMTP服务器
        smtpObj.login('1710695204@qq.com', 'jawbsazwulsofcja')
        # 5. 发送电子邮件
        from_addr = '1710695204@qq.com'  # 发件人
        to_addr = email  # 收件人
        code = cls.generate_code()
        message = MIMEText(f"""用户{inviter}邀请您加入团队空间{team_name}一起协作，请点击下方链接确认加入！
                                            您的确认链接为: {url}  
                                            24小时内有效, 请及时使用，谢谢~""", 'plain',
                           'utf-8')  # 正文
        message['From'] = cls._format_addr('YuGong Wiki <%s>' % from_addr)  # 发件人
        message['To'] = cls._format_addr('Wiki Lover <%s>' % to_addr)  # 收件人
        subject = 'YuGong Wiki 协作邀请'
        message['Subject'] = Header(subject, 'utf-8')  # 主题

        smtpObj.sendmail(from_addr, [to_addr], message.as_string())
        # 6. 从服务器断开
        smtpObj.quit()
        return code

    @classmethod
    def send_email_code(cls, email: str):
        # 1. 连接到SMTP服务器
        smtpObj = smtplib.SMTP('smtp.qq.com', 587)
        # 2. 发送SMTP的“HELLO”消息
        smtpObj.ehlo()
        # 3. 开始TLS加密
        smtpObj.starttls()
        # 4. 登陆到SMTP服务器
        smtpObj.login('1710695204@qq.com', 'jawbsazwulsofcja')
        # 5. 发送电子邮件
        from_addr = '1710695204@qq.com'  # 发件人
        to_addr = email  # 收件人
        code = cls.generate_code()
        message = MIMEText(f"""欢迎注册愚公WIKI!
                                        您的验证码为: {code}, 60秒内有效, 请及时使用，谢谢~""", 'plain', 'utf-8')  # 正文
        message['From'] = cls._format_addr('YuGong Wiki <%s>' % from_addr)  # 发件人
        message['To'] = cls._format_addr('Wiki Lover <%s>' % to_addr)  # 收件人
        subject = 'YuGong Wiki 邮箱验证码'
        message['Subject'] = Header(subject, 'utf-8')  # 主题

        smtpObj.sendmail(from_addr, [to_addr], message.as_string())
        # 6. 从服务器断开
        smtpObj.quit()
        return code

    @classmethod
    def generate_code(cls):
        code = ''
        for i in range(6):
            code += str(random.choice(string.ascii_lowercase+string.digits))
        return code
    @classmethod
    def _format_addr(cls, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

